//
//  QLMInvoicesViewController.m
//  Xiaomakuaixiu
//
//  Created by 邬俊涛 on 2018/3/9.
//  Copyright © 2018年 hwd. All rights reserved.
//

#import "QLMInvoicesViewController.h"
#import "QLMProtectViewController.h"
#import "QLMNormalViewController.h"
#import "QLMPersonViewController.h"
#import "QLMAddInvoicesVC.h"

#import "QLMInvoiceNorModel.h"
#import "QLMInvoiceProModel.h"

static CGFloat const titleH = 44;
static CGFloat const navBarH = 0;
static CGFloat const maxTitleScale = 1.0;

@interface QLMInvoicesViewController ()<UIScrollViewDelegate>{
    QLMInvoiceNorModel *invoiceNorModel;
    QLMInvoiceProModel *invoiceProModel;
    
    QLMNormalViewController *vc1;
    QLMProtectViewController *vc2;
    
    NSString *custType;
    
    QLMCustomTipView *tipView;
    QLMCustomTipView *tipView2;
    
    UIButton *img1btn;
    UIButton *img2btn;
}

@property (nonatomic, weak) UIScrollView *titleScrollView;
@property (nonatomic, weak) UIScrollView *contentScrollView;
@property (nonatomic, weak) UIButton *selTitleButton;
@property (nonatomic, strong) NSMutableArray *buttons;

@end

@implementation QLMInvoicesViewController

- (NSMutableArray *)buttons{
    if (!_buttons){
        _buttons = [NSMutableArray array];
    }
    return _buttons;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setUPnavigation];
    // Do any additional setup after loading the view.
    self.title=@"发票信息";
    custType=@"2";
    invoiceNorModel.invoiceNorArrModel=[NSArray array];
    invoiceProModel.invoiceProArrModel=[NSArray array];
    
    [self setupTitleScrollView];
    [self setupContentScrollView];
    [self addChildViewController];
    [self setupTitle];
    
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.contentScrollView.contentSize = CGSizeMake(self.childViewControllers.count * kScreen_width, 0);
    self.contentScrollView.pagingEnabled = YES;
    self.contentScrollView.showsHorizontalScrollIndicator = NO;
    self.contentScrollView.delegate = self;
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden=NO;
    [self requestInvoicesData];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)setUPnavigation{
    UIButton *rightButton = [UIButton buttonWithType:UIButtonTypeCustom];
    rightButton.frame = CGRectMake(0, 0, 44, 44);
    [rightButton setImage:[UIImage imageNamed:@"tj_icon"] forState:UIControlStateNormal];
    [rightButton setBackgroundColor:[UIColor clearColor]];
    rightButton.contentHorizontalAlignment=UIControlContentHorizontalAlignmentRight;
    [rightButton addTarget:self action:@selector(rightClick) forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem *fixedSpace = [[UIBarButtonItem alloc]
                                   initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace
                                   target:nil
                                   action:nil];
    fixedSpace.width = 0;
    
    UIBarButtonItem *leftItem = [[UIBarButtonItem alloc] initWithCustomView:rightButton];
    self.navigationItem.rightBarButtonItems = [NSArray arrayWithObjects:fixedSpace,leftItem,nil];
}

- (void)rightClick{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction *action = [UIAlertAction actionWithTitle:@"新增公司普票" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        [self addInvoiceclick:@"2"];
    }];
    [alert addAction:action];
    
    UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"新增公司专票" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        [self addInvoiceclick:@"3"];
    }];
    [alert addAction:action2];
    
    UIAlertAction *action3 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
    }];
    [alert addAction:action3];
    
    [self presentViewController:alert animated:YES completion:nil];
}

- (void)addInvoiceclick:(NSString *)str{
    QLMAddInvoicesVC *addInvoiceVC=[QLMAddInvoicesVC new];
    custType=str;
    addInvoiceVC.custType=str;
    if([str isEqualToString:@"2"]){
       addInvoiceVC.title=@"新增公司普票";
    }else{
       addInvoiceVC.title=@"新增公司专票";
    }
    self.hidesBottomBarWhenPushed=YES;
    [self.navigationController pushViewController:addInvoiceVC animated:YES];
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/
- (void)requestInvoicesData{
    NSString *userID=[[NSUserDefaults standardUserDefaults] objectForKey:kLoginUserId];
    NSMutableDictionary *paraDic=[NSMutableDictionary dictionary];
    [paraDic setObject:userID forKey:@"userId"];
    [paraDic setObject:@"1" forKey:@"saleCustId"];
    [paraDic setObject:@"1" forKey:@"pageNo"];
    [paraDic setObject:@"100" forKey:@"pageSize"];
    
    [self.view makeToastActivity:CSToastPositionCenter];
    [ClientTool postUrlPath:@"/rest/appUser/findMyInvoices" withParamers:paraDic andBody:nil
                    success:^(id responseObject){
                        [self.view hideToastActivity];
                        NSInteger code = [[responseObject objectForKey:@"flag"] integerValue];
                        if (code == 1) {
                            
                            NSArray *invoiceArr=[NSArray arrayWithArray:responseObject[@"rows"]];
                            NSMutableArray *norArr=[NSMutableArray array];
                            NSMutableArray *proArr=[NSMutableArray array];
                            
                            for (int i=0;i<invoiceArr.count;i++) {
                                
                                if ([[invoiceArr[i] objectForKey:@"custType"] integerValue]==2) {
                                    [norArr addObject:invoiceArr[i]];
                                }else if ([[invoiceArr[i] objectForKey:@"custType"] integerValue]==3){
                                    [proArr addObject:invoiceArr[i]];
                                }
                                
                            }
                            
                            NSDictionary *tmp1Dic=[NSDictionary dictionaryWithObjectsAndKeys:norArr,@"invoiceNorArrModel", nil];
                            invoiceNorModel=[[QLMInvoiceNorModel alloc] init];
                            invoiceNorModel.invoiceNorArrModel=[NSArray arrayWithArray:tmp1Dic[@"invoiceNorArrModel"]];

                            if (invoiceNorModel.invoiceNorArrModel.count==0) {
                                tipView.hidden = NO;
                            }else{
                                tipView.hidden = YES;
                            }
                            NSDictionary *tmp2Dic=[NSDictionary dictionaryWithObjectsAndKeys:proArr,@"invoiceProArrModel", nil];
                            invoiceProModel=[[QLMInvoiceProModel alloc] init];
                            invoiceProModel.invoiceProArrModel=[NSMutableArray arrayWithArray:tmp2Dic[@"invoiceProArrModel"]];
                            if (invoiceProModel.invoiceProArrModel.count==0) {
                                tipView2.hidden = NO;
                            }else{
                                tipView2.hidden = YES;
                            }
                            vc1.invoiceNorModel=invoiceNorModel;
                            [vc1.normaltableview reloadData];
                            [vc2 setInvoiceProModel:invoiceProModel];
                        }else{
                            ETToast(responseObject[@"msg"]);
                        }
                    }failure:^(NSError *error){
                        [self.view hideToastActivity];
                        ETToast(@"服务器连接失败");
                    }
     ];
}

#pragma mark - 设置头部标题栏
- (void)setupTitleScrollView{
    // 判断是否存在导航控制器来判断y值
    CGFloat y = self.navigationController ? navBarH : 0;
    CGRect rect = CGRectMake(0, y, kScreen_width, titleH);
    
    UIScrollView *titleScrollView = [[UIScrollView alloc] initWithFrame:rect];
    titleScrollView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:titleScrollView];
    
    self.titleScrollView = titleScrollView;
}

#pragma mark - 设置内容
- (void)setupContentScrollView{
    CGFloat y = CGRectGetMaxY(self.titleScrollView.frame);
    CGRect rect = CGRectMake(0, y, kScreen_width, kScreen_height - navBarH);
    
    UIScrollView *contentScrollView = [[UIScrollView alloc] initWithFrame:rect];
    [self.view addSubview:contentScrollView];
    
    self.contentScrollView = contentScrollView;
    
    tipView=[QLMCustomTipView sharedInstance];
    tipView.hidden = YES;
    [contentScrollView addSubview:tipView];
    
    tipView2=[QLMCustomTipView sharedInstance:CGRectMake(kScreen_width, 0, kScreen_width, 200)];
    tipView2.hidden = YES;
    [contentScrollView addSubview:tipView2];
}

#pragma mark - 添加子控制器
- (void)addChildViewController{
//    QLMPersonViewController *vc = [[QLMPersonViewController alloc] init];
//    vc.title = @"个人普票";
//    [self addChildViewController:vc];
    
    vc1 = [[QLMNormalViewController alloc] init];
    vc1.title = @"公司普票";
    [self addChildViewController:vc1];
    
    vc2 = [[QLMProtectViewController alloc] init];
    vc2.title = @"公司专票";
    [self addChildViewController:vc2];
}

#pragma mark - 设置标题
- (void)setupTitle{
    NSUInteger count = self.childViewControllers.count;
    
    CGFloat x = 0;
    CGFloat w = kScreen_width/count;
    CGFloat h = titleH;
    
    for (int i = 0; i < count; i++){
        UIViewController *vc = self.childViewControllers[i];
        x = i * w;
        CGRect rect = CGRectMake(x, 0, w, h);
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        btn.frame=rect;
        btn.tag = i;
        [btn setTitle:vc.title forState:UIControlStateNormal];
        [btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        btn.titleLabel.font = [UIFont systemFontOfSize:15];
        [btn addTarget:self action:@selector(chick:) forControlEvents:UIControlEventTouchDown];
        
        [self.buttons addObject:btn];
        [self.titleScrollView addSubview:btn];
        
        if (i == 0){
            [self chick:btn];
        }
        
        UIButton *imgbtn = [UIButton buttonWithType:UIButtonTypeCustom];
        imgbtn.frame=CGRectMake(65+w*i, h-3, w-65*2, 3);
        imgbtn.tag = i+10;
        if (i==0) {
            imgbtn.hidden=NO;
            img1btn=imgbtn;
            [imgbtn setBackgroundColor:kNavigationBarColor];
        }else{
            imgbtn.hidden=YES;
            img2btn=imgbtn;
            [imgbtn setBackgroundColor:[UIColor redColor]];
        }
        [self.titleScrollView addSubview:imgbtn];
    }
    self.titleScrollView.contentSize = CGSizeMake(count * w, 0);
    self.titleScrollView.showsHorizontalScrollIndicator = NO;
}

// 按钮点击
- (void)chick:(UIButton *)btn{
    [self selTitleBtn:btn];
    
    NSUInteger i = btn.tag;
    CGFloat x = i * kScreen_width;
    
    [self setUpOneChildViewController:i];
    self.contentScrollView.contentOffset = CGPointMake(x, 0);
    
    UIButton *leftButton = self.buttons[i];
    UIButton *rightButton = nil;
    if (i+1 < self.buttons.count) {
        rightButton = self.buttons[i+1];
    }
    
    if (i==0) {
        custType=@"2";
        img1btn.hidden=NO;
        img2btn.hidden=YES;
        [leftButton setTitleColor:kNavigationBarColor forState:UIControlStateNormal];
        [rightButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    }else{
        custType=@"3";
        img1btn.hidden=YES;
        img2btn.hidden=NO;
        [leftButton setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
        [rightButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    }
    
}
// 选中按钮
- (void)selTitleBtn:(UIButton *)btn{
    [self.selTitleButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    self.selTitleButton.transform = CGAffineTransformIdentity;
    
    [btn setTitleColor:kNavigationBarColor forState:UIControlStateNormal];
    btn.transform = CGAffineTransformMakeScale(maxTitleScale, maxTitleScale);
    
    self.selTitleButton = btn;
    [self setupTitleCenter:btn];
}

- (void)setUpOneChildViewController:(NSUInteger)i{
    CGFloat x = i * kScreen_width;
    UIViewController *vc = self.childViewControllers[i];
    if (vc.view.superview) {
        return;
    }
    vc.view.frame = CGRectMake(x, 0, kScreen_width, kScreen_height - self.contentScrollView.frame.origin.y-QLM_StatusBarAndNavigationBarHeight-IOS11_OR_LATER_SPACE(34));
    [self.contentScrollView addSubview:vc.view];
}

- (void)setupTitleCenter:(UIButton *)btn{
    CGFloat offset = btn.center.x - kScreen_width * 0.5;
    if (offset < 0){
        offset = 0;
    }
    
    CGFloat maxOffset = self.titleScrollView.contentSize.width - kScreen_width;
    if (offset > maxOffset){
        offset = maxOffset;
    }
    [self.titleScrollView setContentOffset:CGPointMake(offset, 0) animated:YES];
}

#pragma mark - UIScrollViewDelegate
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    NSUInteger i = self.contentScrollView.contentOffset.x / kScreen_width;
    [self selTitleBtn:self.buttons[i]];
    [self setUpOneChildViewController:i];
    UIButton *leftButton = self.buttons[i];
    UIButton *rightButton = nil;
    if (i+1 < self.buttons.count) {
        rightButton = self.buttons[i+1];
    }
    if (i==0) {
        custType=@"2";
        img1btn.hidden=NO;
        img2btn.hidden=YES;
        [leftButton setTitleColor:kNavigationBarColor forState:UIControlStateNormal];
        [rightButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    }else{
        custType=@"3";
        img1btn.hidden=YES;
        img2btn.hidden=NO;
        [leftButton setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
        [rightButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    }
}

@end
